package com.itheima.reggie.controller;

import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerOutput;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.utils.SendMsgUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.management.snmp.jvmmib.JvmThreadInstanceTableMeta;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /*
    套餐和菜品表为多对多的关系，此时第三方表来维持。
     */
    @PostMapping
    @ApiOperation("新增套餐，以及菜品信息。接口")
    public R saveSetmeal(@RequestBody SetmealDto setmealDto) {
        setmealService.saveSetmeal(setmealDto);
        Set keys = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);
        return R.success(null);
    }

    @GetMapping("/page")
    @ApiOperation("套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页页数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名字",required = false)
    })
    public R setmealManagePage(int page, int pageSize, String name) {
        /*
        1.写出套餐表的分页查询，发现套餐分类字段不显示
        2.所以说写个包含套餐分类名字的分页查询
        3.实际上就是封装到一个包含名字的实体类中进行分页查询
         */

        Page<Setmeal> setmealPageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        if (name != null) {
            lqw.like(Setmeal::getName, name);
        }
        lqw.orderByDesc(Setmeal::getUpdateTime);//根据更新时间降序
        setmealService.page(setmealPageInfo, lqw);

        Page<SetmealDto> setmealDtoPageInfo = new Page<>(page, pageSize);

        BeanUtils.copyProperties(setmealPageInfo, setmealDtoPageInfo, "records");
        List<Setmeal> setmeals = setmealPageInfo.getRecords();
        List<SetmealDto> collect = setmeals.stream().map((item) -> {//取出每个套餐实体类
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);//通过菜品id查询
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPageInfo.setRecords(collect);
        return R.success(setmealDtoPageInfo);
    }


    @PostMapping("/status/{id}")
    @ApiOperation(value = "操作状态接口")
    public R setmealStatusStop(@PathVariable Long id, @RequestParam List<Long> ids) {
        if (id == 1 && ids.size() > 1) {//表示批量起售状态
            LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            lqw.in(Setmeal::getId, ids);
            List<Setmeal> list = setmealService.list(lqw);//select * from setmeal where id in(1,2)
            List<Setmeal> collect = list.stream().map((item) -> {//此时item为setmeal对象
                item.setStatus(1);
                return item;
            }).collect(Collectors.toList());
            setmealService.updateBatchById(collect);
        } else if (id == 0 && ids.size() > 1) {//表示批量停售状态
            LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            lqw.in(Setmeal::getId, ids);
            List<Setmeal> list = setmealService.list(lqw);//select * from setmeal where id in(1,2)
            List<Setmeal> collect = list.stream().map((item) -> {//此时item为setmeal对象
                item.setStatus(0);
                return item;
            }).collect(Collectors.toList());
            setmealService.updateBatchById(collect);
        } else {
            LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            lqw.in(Setmeal::getId, ids);
            List<Setmeal> list = setmealService.list(lqw);//select * from setmeal where id in(1,2)
            List<Setmeal> collect = list.stream().map((item) -> {//此时item为setmeal对象
                if (item.getStatus() == 1) {
                    item.setStatus(0);
                } else {
                    item.setStatus(1);
                }
                return item;
            }).collect(Collectors.toList());
            setmealService.updateBatchById(collect);
        }

//        Integer status = setmeal.getStatus();
//        if (status==1){
//            setmeal.setStatus(0);
//        }else {
//            setmeal.setStatus(1);
//        }
//        setmealService.updateById(setmeal);
        Set keys = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);
        return R.success(null);
    }

    //    @PostMapping("/status/1")
//    public R setmealStatusRun(@RequestParam Long ids){
//        Setmeal setmeal = setmealService.getById(ids);
//        Integer status = setmeal.getStatus();
//        if (status==1){
//            setmeal.setStatus(0);
//        }else {
//            setmeal.setStatus(1);
//        }
//        setmealService.updateById(setmeal);
//        return R.success(null);
//    }
    @DeleteMapping
    @ApiOperation(value = "删除套餐接口")
    public R delete(@RequestParam List<Long> ids) {
        setmealService.delete(ids);
        Set keys = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);
        return R.success(null);
    }

    /*
    用户端，移动端
        根据分类id查询出对应套餐
     */
    @GetMapping("/list")//@RequestParam 不支持直接传递实体类的方式
    @ApiOperation(value = "查询套餐接口")
    public R listSetmeal(Setmeal setmeal) {
        List<Setmeal> list = null;
        String setmealKey = "setmeal_" + setmeal.getCategoryId() + "_" + setmeal.getStatus();
        list = (List<Setmeal>) redisTemplate.opsForValue().get(setmealKey);
        if (list != null) {
            return R.success(list);
        }
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(Setmeal::getStatus, setmeal.getStatus());
        list = setmealService.list(lqw);
        redisTemplate.opsForValue().set(setmealKey, list, 60, TimeUnit.MINUTES);
        return R.success(list);
    }

    /*
    修改套餐进行数据回显，接受的是套餐id，根据套餐id找到套餐菜品表所有信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "修改套餐数据回显接口")
    public R dataHuiXian(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.dateHX(id);
        return R.success(setmealDto);
    }

    /*
    对管理页面套餐数据进行修改
     */
    @PutMapping
    @ApiOperation(value = "对管理页面套餐数据进行修改")
    public R updateSetmeal(@RequestBody SetmealDto setmealDto) {
        setmealService.updateSetmeal(setmealDto);
        return R.success(null);
    }

}
